<?php

class UsersController extends BaseController {

	function index() {
		return View::make('users');
	}
	function showLogin() {
		return View::make('users.login-form');
	}
	function doLogin() {
		// validate the info, create rules for the inputs
		$rules = array(
			'username'    => 'required', // make sure the email is an actual email
			'password' => 'required|min:3' // password can only be alphanumeric and has to be greater than 3 characters
		);

		// run the validation rules on the inputs from the form
		$validator = Validator::make(Input::all(), $rules);

		// set the remember me cookie if the user check the box
        $remember = (Input::has('rememberme')) ? true : false;

		// if the validator fails, redirect back to the form
		if ($validator->fails()) {
			Session::flash('message', trans('app.wronguserlogin'));
			return Redirect::to('login')
				->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
		}
		else {
			// create our user data for the authentication
			$userdata = array(
				'username' 	=> Input::get('username'),
				'password' 	=> Input::get('password')
			);

			// attempt to do the login
			if (Auth::attempt($userdata, $remember)) {
				// validation successful!
				return Redirect::to('/multi-product-ads');
			}
			else {	 	
				// validation not successful, send back to form	
				Session::flash('message', trans('app.wronguserlogin'));
				return Redirect::to('login')
				->withInput(Input::except('password'));
			}
		}
	}
	function loginFacebook() {
		// get data from input
	    $code = Input::get( 'code' );

	    // get fb service
	    $fb = OAuth::consumer( 'Facebook' );

	    // check if code is valid

	    // if code is provided get user data and sign in
	    if ( !empty( $code ) ) {

	        // This was a callback request from facebook, get the token
	        $token = $fb->requestAccessToken( $code );
	        // Send a request with it
	        $result = json_decode( $fb->request( '/me' ), true );

	        $userHasAccount = User::select('id', 'fb_user_id')->where('fb_user_id', $result['id'])->first();
	        if (!$userHasAccount && !empty($result)) {
	        	$user = new User;
	        	$result['name'] = isset($result['name']) ? $result['name'] : $result['id'];
	        	$result['email'] = isset($result['email']) ? $result['email'] : $result['id'] . '@facebook.com';

		        $user->name = $result['name'];
		        $user->username = isset($result['email']) ? $result['email'] : $result['id'];
		        $user->name = $result['name'];
		        $user->fb_user_id = $result['id'];
		        $user->access_token = $token->getAccessToken();
		        $user->email = $result['email'];
		        $user->registration_type = 'facebook';
		        // free 1 month trial
		        $user->expried_time = date('Y-m-d H:i:s', (time() + 30 * 24 * 60 * 60));
		        $user->save();
		        $userId = $user->id;
	        }
	        else {
		        $userId = $userHasAccount->id;
		        User::where('id', $userId)->update(array('access_token' => $token->getAccessToken()));
		    }
	        // Log him in
	        Auth::loginUsingId($userId);
	       /* $perms = json_decode($fb->request('/v2.2/me/permissions'), true);
	        $fbConf = Config::get("oauth-4-laravel::consumers.Facebook.scope");
	        array_push($fbConf, 'public_profile');// add default permission

	        $grandedPerms = [];
			if(!empty($perms['data'])) {
				foreach($perms['data'] as $per) {
					if($per['status'] == 'granted') {
						array_push($grandedPerms, $per['permission']);
					}
				}
			}
			print_r($fbConf);
			echo '<br>';
			print_r($grandedPerms);
			echo '<br>';
			dd(array_diff($fbConf, $grandedPerms));*/

			$response = $fb->request('/v2.2/me/accounts');
			$pageData = json_decode($response, true);
			$arrPage = [];
			if (isset($pageData['data']) && !empty($pageData['data'])) {
				foreach ($pageData['data'] as $pages) {
					if( !Fbpage::where('user_id', $userId)->where('fb_page_id', $pages['id'])->count()) {
						array_push($arrPage, array(
							'fb_page_id' => $pages['id'],
							'user_id' 	 => $userId,
							'page_name'	 => $pages['name'],
							'page_token' => $pages['access_token'],
							'page_perms' => json_encode($pages['perms']),
							));
					}
					else {
						Fbpage::where('user_id', $userId)->where('fb_page_id', $pages['id'])->update(array(
							'fb_page_id' => $pages['id'],
							'user_id' 	 => $userId,
							'page_name'	 => $pages['name'],
							'page_token' => $pages['access_token'],
							'page_perms' => json_encode($pages['perms']),
							));
					}
				}
			}
			else {
				return View::make('users.fbcallback')
	        		->with('error', trans('app.loginfail_or_nopage'));
			}
			if (!empty($arrPage)) {
				// Fbpage::where('user_id', $userId)->delete();
				Fbpage::insert($arrPage);
			}
			// subscribe for realtime API
			$pages = Fbpage::where('user_id', Auth::user()->id)->get();
			Fbpage::fbRealTimeSubForPage($pages);
	        return View::make('users.fbcallback')
	        ->with('message', trans('app.loggedwithfb'));
	    }
	    // if not ask for permission first
	    else {
	        // get fb authorization
	        $url = $fb->getAuthorizationUri();
	        // return to facebook login url
	         return Redirect::to( (string)$url );
	    }
	}
}